import CommonUtil from '../utils/common'

let _router = null

export default (router) => {
  _router = router
  return (dataList) => {
    const dataMap = {}
    dataList = dataList.map(i => {
      const item = {
        name: i.code,
        parentId: i.parentId,
        id: i.id,
        path: i.uri == '' ? null : i.uri,
        component: i.component == '' ? null : i.component,
        redirect: i.redirect,
        hidden: CommonUtil.toBool(i.hidden),
        hideChildrenInMenu: CommonUtil.toBool(i.hideChildren),
        meta: {
          authorize: [],
          view: i.component == '' ? null : i.component,
          keepAlive: CommonUtil.toBool(i.keepAlive),
          icon: i.icon && i.icon != '' ? i.icon : null,
          title: i.name,
          type: i.type,
          target: i.target === '1' ? null : i.target === '3' ? '_blank' : i.code
        }
      }
      if (!item.meta.target) {
        item.meta.renderInBasicLayout = true
      }
      item.redirect == '' && (delete item.redirect)
      dataMap[item.id] = item
      return item
    })

    let menuTree = listToTree(dataList, dataMap)

    let root = _router.getRoot()
    root.children = root.children.concat(menuTree)
    root = generate([root])[0]

    setDefaultRedirect(root, root)

    hideChildren(root.children)

    return root
  }
}

/**
 * 构建path、name、component、redirect
 */
function generate (treeNodes, parent) {
  return treeNodes.map(item => {
    let component = item.component
    if (component && CommonUtil.isString(component)) {
      item.component = _router.getViews()[component]
    }
    if (item.path == null || item.path === undefined) {
      if (parent && parent.path) {
        item.path = (parent.path + '/' + item.name).replace('//', '/')
      } else {
        item.path = ('/' + item.name).replace('//', '/')
      }
    }
    if (parent && !parent.redirect && parent.path == item.path) {
      parent.redirect = parent.redirect
    }
    parent && parent.hideChildrenInMenu && (item.meta.hidden = true)
    parent && (item.parent = parent)
    // parent && parent.name && parent.name !== '' && (item.name = parent.name + '#' + item.name)
    generate(item.children || [], item)
    return item
  })
}

/**
 * 构建树结构
 */
function listToTree (menuList, menuMap) {
  const menuTree = []
  menuList.map(i => {
    if (i.parentId == '0') {
      menuTree.push(i)
    } else {
      const parent = menuMap[i.parentId]
      if (!parent) {
        console.error(`找不到 "${i.meta.title}" 的上级菜单: {id: ${i.id}, parentId: ${i.parentId}}`);
        return
      }
      !parent.children && (parent.children = [])
      if (i.meta.type == '3') {
        parent.meta.authorize.push(i.name.split(':').pop())
        if (!i.component) {
          return
        }
      }
      parent.children.push(i)
    }
  })
  return menuTree
}

function setDefaultRedirect (route, root) {
  if (root.redirect) {
    return true
  }
  if (route.redirect) {
    root.redirect = route.redirect
    return true
  }
  if (route.hideChildrenInMenu || !route.children || route.children.length == 0) {
    root.redirect = route.path
  } else {
    route.children.find(i => {
      return setDefaultRedirect(i, root)
    })
  }
}

function hideChildren (routes) {
  routes.map(r => {
    if (r.children) {
      if (r.children.length == 0) {
        r.hideChildrenInMenu = true
      } else {
        // 下级节点不为功能菜单并且下级节点没有要显示的菜单
        const c = r.children.find(c => {
          return c.meta?.type != '3' && !c.hidden
        })
        !c && (r.hideChildrenInMenu = true)
      }
    }
    hideChildren(r.children || [])
  })
}
